package com.mall507.fivepeaks.widget.xpopupwindow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.util.Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城列表条件筛选弹出框
 */
public class XStoreListPW extends PopupWindow implements OnClickListener{

  private Context context;
  private View contentView;
  private CallBack callBack;
  private ListView listView;
  /**弹窗数据源*/
  private List<HashMap<String, String>> dataList;
  /**所有选择数据源*/
  private List<HashMap<String, String>> items;

  public XStoreListPW(Context context,List<HashMap<String, String>> dataList,List<HashMap<String, String>> items, CallBack callBack) {
    super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    this.context = context;
    this.dataList=dataList;
    this.items=items;
    this.callBack = callBack;
    initPopupWindowView();
  }

  /**
   * @author 贺子航  2015/04/10 10:51
   * @description 初始化布局
   */
  @SuppressLint("NewApi")
  public void initPopupWindowView() {
    LayoutInflater inflater = LayoutInflater.from(context);
    // 获取自定义布局文件shoptype_item.xml的视图
    contentView = inflater.inflate(R.layout.view_xstore_list_pw, null, false);
    // 自定义view添加触摸事件
    contentView.setOnTouchListener(new View.OnTouchListener() {
      public boolean onTouch(View v, MotionEvent event) {
        if (isShowing()) {
            dismiss();
        }
        return false;
      }
    });
    contentView.findViewById(R.id.reset).setOnClickListener(this);
    contentView.findViewById(R.id.confirm).setOnClickListener(this);
    listView=(ListView) contentView.findViewById(R.id.listView);
    listView.setAdapter(new listViewAdapter(context, dataList, R.layout.item_lv_xstore_list_pw, new String[]{"name1","name2"}, new int[]{R.id.name1,R.id.name2}));
    listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    setContentView(contentView);
  }
  
  /**
   * ListView适配器
   */
  private class listViewAdapter extends SimpleAdapter implements OnClickListener{
		public listViewAdapter(Context context,List<? extends Map<String, ?>> data, int resource,String[] from, int[] to) {
			super(context, data, resource, from, to);
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View v=super.getView(position, convertView, parent);
			TextView name1=(TextView) v.findViewById(R.id.name1);
			TextView name2=(TextView) v.findViewById(R.id.name2);
			HashMap<String, String> map=dataList.get(position);
			//第一列
			if(!Util.isEmpty(name1.getText().toString())){
				v.findViewById(R.id.name1Lin).setVisibility(View.VISIBLE);
				v.findViewById(R.id.name1Lin).setTag(position);
				if("1".equals(map.get("selected1"))){
					name1.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.comn_hook_blue, 0);
					name1.setTextColor(Color.parseColor("#3AA6AC"));
					v.findViewById(R.id.name1Line).setVisibility(View.VISIBLE);
				}else{
					name1.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					name1.setTextColor(Color.parseColor("#666666"));
					v.findViewById(R.id.name1Line).setVisibility(View.INVISIBLE);
				}
			}else{
				v.findViewById(R.id.name1Lin).setVisibility(View.INVISIBLE);
			}
			//第二列
			if(!Util.isEmpty(name2.getText().toString())){
				v.findViewById(R.id.name2Lin).setVisibility(View.VISIBLE);
				v.findViewById(R.id.name2Lin).setTag(position);
				if("1".equals(map.get("selected2"))){
					name2.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.comn_hook_blue, 0);
					name2.setTextColor(Color.parseColor("#3AA6AC"));
					v.findViewById(R.id.name2Line).setVisibility(View.VISIBLE);
				}else{
					name2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					name2.setTextColor(Color.parseColor("#666666"));
					v.findViewById(R.id.name2Line).setVisibility(View.INVISIBLE);
				}
			}else{
				v.findViewById(R.id.name2Lin).setVisibility(View.INVISIBLE);
			}
			
			v.findViewById(R.id.name1Lin).setOnClickListener(this);
			v.findViewById(R.id.name2Lin).setOnClickListener(this);
			return v;
		}

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.name1Lin:
				if(View.VISIBLE==view.findViewById(R.id.name1Line).getVisibility()){
					((TextView)view.findViewById(R.id.name1)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					((TextView)view.findViewById(R.id.name1)).setTextColor(Color.parseColor("#666666"));
					view.findViewById(R.id.name1Line).setVisibility(View.INVISIBLE);
					dataList.get((Integer)view.getTag()).put("selected1", "0");
				}else{
					int length=0;
					for(int i=0;i<dataList.size();i++){
						HashMap<String, String> map=dataList.get(i);
						if("1".equals(map.get("selected1"))){
							length++;
						}
						if("1".equals(map.get("selected2"))){
							length++;
						}
					}
					if(length<5){
						((TextView)view.findViewById(R.id.name1)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.comn_hook_blue, 0);
						((TextView)view.findViewById(R.id.name1)).setTextColor(Color.parseColor("#3AA6AC"));
						view.findViewById(R.id.name1Line).setVisibility(View.VISIBLE);
						dataList.get((Integer)view.getTag()).put("selected1", "1");
					}else{
						 Toast toast=Toast.makeText(context, "最多可选5项", Toast.LENGTH_SHORT);
	                     toast.setGravity(Gravity.CENTER, 0, 0);
	                     toast.show();
					}
				}
				break;
			case R.id.name2Lin:
				if(View.VISIBLE==view.findViewById(R.id.name2Line).getVisibility()){
					((TextView)view.findViewById(R.id.name2)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					((TextView)view.findViewById(R.id.name2)).setTextColor(Color.parseColor("#666666"));
					view.findViewById(R.id.name2Line).setVisibility(View.INVISIBLE);
					dataList.get((Integer)view.getTag()).put("selected2", "0");
				}else{
					int length=0;
					for(int i=0;i<dataList.size();i++){
						HashMap<String, String> map=dataList.get(i);
						if("1".equals(map.get("selected1"))){
							length++;
						}
						if("1".equals(map.get("selected2"))){
							length++;
						}
					}
					if(length<5){
					    ((TextView)view.findViewById(R.id.name2)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.comn_hook_blue, 0);
					    ((TextView)view.findViewById(R.id.name2)).setTextColor(Color.parseColor("#3AA6AC"));
					    view.findViewById(R.id.name2Line).setVisibility(View.VISIBLE);
					    dataList.get((Integer)view.getTag()).put("selected2", "1");
					}else{
						Toast.makeText(context, "最多可选5项", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
		}
  }
  
  @Override
  public void onClick(View view) {
	  switch (view.getId()) {
	  case R.id.reset:
		  HashMap<String, String> mapR=new HashMap<String, String>();
		  mapR.put("name", dataList.get(0).get("ifName"));
		  mapR.put("values", "");
		  if(items!=null && items.size()>0){
			  int flag=-1;
			  for(int i=0;i<items.size();i++){
				  //存在该条件选项
				  if(mapR.get("name").equals(items.get(i).get("name"))){
					  flag=i;
				  }
			  }
			  if(flag<0){
				  items.add(mapR);
			  }else{
				  items.get(flag).put("values", mapR.get("values"));
			  }
		  }else{
			  items.add(mapR);
		  }
		  callBack.reset(items);
		  dismiss();
		break;
	  case R.id.confirm:
		  if(dataList!=null && dataList.size()>0){
			  HashMap<String, String> itemsMap=new HashMap<String, String>();
			  itemsMap.put("name", dataList.get(0).get("ifName"));
			  itemsMap.put("values", "");
			  for(int i=0;i<dataList.size();i++){
					HashMap<String, String> map=dataList.get(i);
					if("1".equals(map.get("selected1"))){
						itemsMap.put("values",itemsMap.get("values")+","+map.get("name1"));
					}
					if("1".equals(map.get("selected2"))){
						itemsMap.put("values",itemsMap.get("values")+","+map.get("name2"));
					}
			  }
			  if(itemsMap.get("values").length()>0){
				  itemsMap.put("values", itemsMap.get("values").substring(1, itemsMap.get("values").length()));
			  }
			  if(items!=null && items.size()>0){
				  int flag=-1;
				  for(int i=0;i<items.size();i++){
					  //存在该条件选项
					  if(itemsMap.get("name").equals(items.get(i).get("name"))){
						  flag=i;
					  }
				  }
				  if(flag<0){
					  items.add(itemsMap);
				  }else{
					  items.get(flag).put("values", itemsMap.get("values"));
				  }
			  }else{
				  items.add(itemsMap);
			  }
			  callBack.confirm(items,itemsMap.get("values"));
		  }else{
			  callBack.confirm(items,"");
		  }
		  dismiss();
		break;
	  }
  }
  
  /**
   * 解决android7.0上某些PopuWindow显示位置不正确的
   * */
    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24){
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            setHeight(height);
        }
        setAnimationStyle(0);
        super.showAsDropDown(anchor);
    }
    
    /**
     * 解决android7.0上某些PopuWindow显示位置不正确的
     * */
      @Override
      public void showAsDropDown(View anchor,int xoff,int yoff) {
          if(Build.VERSION.SDK_INT >= 24){
              Rect visibleFrame = new Rect();
              anchor.getGlobalVisibleRect(visibleFrame);
              int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
              setHeight(height);
          }
          setAnimationStyle(0);
          super.showAsDropDown(anchor,xoff,yoff);
      }
  
  /**
   * 结果回调
   */
  public interface CallBack {

    /**
     * 确定
     */
    void confirm(List<HashMap<String, String>> items,String names);

    /**
     * 重置
     */
    void reset(List<HashMap<String, String>> items);
  }

}
